package com.xincheng.shuimalong.fragment.insurance;

import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.xincheng.library.adpater.BaseRecyclerAdapter;
import com.xincheng.library.adpater.TreeRecyclerAdapter;
import com.xincheng.library.adpater.TreeRecyclerViewType;
import com.xincheng.library.adpater.ViewHolder;
import com.xincheng.library.base.BaseItem;
import com.xincheng.library.base.BaseItemData;
import com.xincheng.library.factory.ItemHelperFactory;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.view.TreeItem;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.insurance.ChatActivity;
import com.xincheng.shuimalong.activity.insurance.ChoseFriendGroup;
import com.xincheng.shuimalong.adapter.friend.FriendItemParent;
import com.xincheng.shuimalong.adapter.friend.FriendTreeAdapter;
import com.xincheng.shuimalong.api.AppUrl;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.GetParam;
import com.xincheng.shuimalong.api.PostParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.dialog.FriendDialog;
import com.xincheng.shuimalong.entity.customer.Customer;
import com.xincheng.shuimalong.entity.friend.Friend;
import com.xincheng.shuimalong.fragment.BaseFragment;
import com.xincheng.shuimalong.util.GreenUtil;
import com.xincheng.shuimalong.util.GsonUtil;
import com.xincheng.shuimalong.util.ShowActivity;
import com.xincheng.shuimalong.view.ListItemDecoration;

import java.security.acl.Group;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.annotations.NonNull;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

/**
 * Created by 许浩 on 2017/6/29.
 */

public class FriendFragment extends BaseFragment {
    @BindView(R.id.friend_recyclerview)
    RecyclerView friendRecyclerview;
    TreeRecyclerAdapter treeRecyclerAdapter;
    private List<TreeItem> treeItemList;
    private ArrayList<String> ids = new ArrayList<>();

    public static FriendFragment newInstance() {
        FriendFragment friendFragment = new FriendFragment();
        return friendFragment;
    }

    @Override
    public int getFragmentLayoutId() {
        return R.layout.fragment_friend;
    }

    @Override
    public void initData() {
        treeItemList = ItemHelperFactory.createTreeItemList(new ArrayList<Friend>(), FriendItemParent.class, null, getContext());
        friendRecyclerview.setLayoutManager(new GridLayoutManager(getContext(), 6));
        friendRecyclerview.setItemAnimator(new DefaultItemAnimator());
        friendRecyclerview.addItemDecoration(new ListItemDecoration());
        treeRecyclerAdapter = new TreeRecyclerAdapter();
        treeRecyclerAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(ViewHolder viewHolder, BaseItem baseItem, int position) {
                if(baseItem.getData() instanceof Friend.Data){
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(IntentKey.FRIEND_BEAN, (Friend.Data) baseItem.getData());
                    RongIM.getInstance().startPrivateChat(getContext(), ((Friend.Data) baseItem.getData()).getUser_id(), ((Friend.Data) baseItem.getData()).getNick_name());
//                    ShowActivity.showActivityForResult(getActivity(), ChatActivity.class, bundle, RequestCodeKey.UP_FRIEND_LIST);
                }
            }
        });
        treeRecyclerAdapter.setOnItemLongClickListener(new BaseRecyclerAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(ViewHolder viewHolder, BaseItem baseItem, int position) {
                if (baseItem.getData() instanceof Friend) {
                    showGroupDialog(((Friend) baseItem.getData()).getGroup_id());
                } else if (baseItem.getData() instanceof Friend.Data) {
                    Friend.Data friend = (Friend.Data) baseItem.getData();
                    showDialog(friend);
                }
                return false;
            }
        });
        treeRecyclerAdapter.setDatas(treeItemList);
        friendRecyclerview.setAdapter(treeRecyclerAdapter);
        getFriendList();
    }

    public void getFriendList() {
        RetroSubscrube.getInstance().getSubscrube(GetParam.getFriends(PrefUtil.getString(getContext(), PrefKey.TOKEN, "")), new BaseObserver(getContext()) {
            @Override
            protected void onHandleSuccess(Object data, String msg) {
                try {
                    List<Friend> friends = GsonUtil.parseData(data, new TypeToken<List<Friend>>(){}.getType());
                    treeItemList.clear();
                    treeItemList.addAll(ItemHelperFactory.createTreeItemList(friends, FriendItemParent.class, null, getContext()));
                    treeRecyclerAdapter.setDatas(treeItemList);
                    treeRecyclerAdapter.notifyDataSetChanged();
                    for(Friend friend:friends){
                        for(Friend.Data d:friend.getFriends()){
                            RongIM.getInstance().refreshUserInfoCache(new UserInfo(d.getUser_id(),d.getNick_name(), Uri.parse(d.getFace())));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    @Override
    public void addListener() {

    }

    private FriendDialog groupDialog;

    private void showGroupDialog(final String group_id) {
        if (groupDialog == null) {
            groupDialog = FriendDialog.createDialog(getActivity())
                    .setTvDeleteListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            groupDialog.dismiss();
                            if (groupDialog.getId().equals("0.0")) {
                                showToastMsg("不能删除该分组");
                            } else {
                                RetroSubscrube.getInstance().postSubscrube(AppUrl.DEL_GROUP,
                                        PostParam.delGroup(PrefUtil.getString(getContext(), PrefKey.TOKEN, ""), groupDialog.getId())
                                        , new BaseObserver(getContext()) {
                                            @Override
                                            protected void onHandleSuccess(Object data, String msg) {
                                                showToastMsg(msg);
                                                getFriendList();
                                            }
                                        });
                            }
                        }
                    })
                    .setTvMoveGone();
        }
        groupDialog.setId(group_id);
        groupDialog.show();
    }

    private FriendDialog friendDialog;

    private void showDialog(final Friend.Data friendBean) {
        if (friendDialog == null) {
            friendDialog = FriendDialog.createDialog(getActivity())
                    .setTvDeleteListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            friendDialog.dismiss();
                            RetroSubscrube.getInstance().postSubscrube(AppUrl.DEL_FRIENDS,
                                    PostParam.delFriends(PrefUtil.getString(getContext(), PrefKey.TOKEN, ""), friendDialog.getId())
                                    , new BaseObserver(getContext()) {
                                        @Override
                                        protected void onHandleSuccess(Object data, String msg) {
                                            showToastMsg(msg);
                                            GreenUtil.getInstances().deleteHisory(friendDialog.getId());
                                            getFriendList();
                                        }
                                    }
                            );
                        }
                    })
                    .setTvMoveListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            friendDialog.dismiss();
                            ids.add(friendDialog.getId());
                            Bundle bundle = new Bundle();
                            bundle.putStringArrayList(IntentKey.FRIEND_IDS, ids);
                            ShowActivity.showActivityForResult(getActivity(), ChoseFriendGroup.class, bundle, RequestCodeKey.UP_GROUPLIST);
                        }
                    });
        }
        friendDialog.setId(friendBean.getUser_id());
        friendDialog.show();
    }
}
